/**
 * @description 唤起支付请求
 */
import { payUrl } from "@/config"
import { isEmpty } from "@/utils/check"
import { mapGetters } from "vuex"

export default {
  data() {
    return {}
  },
  computed: {
    ...mapGetters(["pwy", "webEvn"])
  },
  methods: {
    /**
     * @description  继续支付（不走预支付接口）
     */
    handleContinuePay() {
      if (uni.$uniPlatform === "web") {
        this.webCreateOrderPay({ payMoney: this.needPay, orderId: this.options.orderId, orderType: this.options.orderType })
      } else {
        this.createOrderPay({ payMoney: this.needPay, orderId: this.options.orderId })
      }
    },
    /**
     * @description 唤起支付
     * @param {orderId,payMoney} options
     * @param {string} options.orderId 订单id
     * @param {string} options.payMoney 支付金额
     * @returns
     */
    createOrderPay(options) {
      if (options.payMoney > 0 && !this.payType) {
        return uni.$toast("请选择支付方式")
      }
      this.options.success = options.success || this.options.success
      this.options.fail = options.fail || this.options.fail
      let query = {
        front_url: `${payUrl.toBackUrl}?orderId=${options.orderId}&name=ailai&orderType=${this.options.orderType}`,
        payType: this.payType, // 选择的支付类型
        orderType: this.options.orderType, // 订单类型
        tradeType: "JSAPI",
        orderId: options.orderId, // 订单id
        payMoney: options.payMoney, // 需要支付的钱
        activityId: this.options.activityId || ""
      }
      if (this.payType === "dceppay") {
        query.tradeType = "minipro"
        query.payType = "dceppay"
      }

      uni.$api.pay.createOrderPay(query).then((resultData) => {
        uni.$setCache("payStatus", 1)
        const wxData = resultData.weixinpay
        const payloadParent = resultData.payload
        const payloadChild = payloadParent?.payload
        if (resultData.payType === "dceppay" && payloadChild.appid) {
          // 跳转去第三方小程序支付
          uni.navigateToMiniProgram({
            appId: payloadChild.appid,
            path: payloadChild.path, //time的值为当前时间的time值
            extraData: {
              URL: encodeURI(resultData.payload.action) //包含接口参数的全链接
            },
            envVersion: payloadChild.envVersion, //develop开发版、trial体验版、release正式版
            success: () => {
              this.paySuccess(query)
            }
          })
        } else if (payloadParent && ["REDIRECT", "POST"].includes(payloadParent.method) && payloadParent.action) {
          // 小程序内嵌h5支付
          if (payloadChild.length || Object.keys(payloadChild).length) {
            const src = `${payUrl.toPayWeb}?param=${JSON.stringify(payloadChild)}&action=${payloadParent.action}&method=${payloadParent.method}`
            uni.$setCache("webviewSrc", src)
          } else {
            uni.$setCache("webviewSrc", payloadParent.action)
          }
          this.toView({
            url: "pages/utils/webview/webview"
          })
        } else {
          // 微信小程序支付
          uni.$pay.weChatMpPay(
            wxData,
            () => {
              this.paySuccess(query)
            },
            (err) => {
              this.payError(err, query)
            }
          )
        }
      })
    },

    /**
     * @description: web平台创建订单支付
     * @return {*}
     */
    webCreateOrderPay(options = {}, callbacks = {}) {
      if (this.payType) {
        this.options.success = callbacks.success || this.options.success
        this.options.fail = callbacks.fail || this.options.fail
        options.url = window.location.href
        options.payType = this.payType
        options.tradeType = "JSAPI"
        const { origin, pathname, search, hash, href } = window.location
        if (isEmpty(options.frontUrl))
          options.frontUrl = href.includes("?")
            ? `${origin}${pathname}${search}${hash}&pwy=${this.pwy}&evn=${this.webEvn}`
            : `${origin}${pathname}${search}${hash}?pwy=${this.pwy}&evn=${this.webEvn}`
        uni.$api.pay.createOrderPay(options).then((res) => {
          const type = res.type
          const payload = res.payload
          uni.$setCache("payStatus", 1)
          // const payType = res.payType
          if (type === "form") {
            if (payload.method.toLocaleLowerCase() === "redirect") {
              window.location.href = payload.action
            } else {
              uni.$formSubmit(payload.action, payload.method, payload.payload)
            }
          } else if (type === "sdk") {
            uni.$auth.sdk
              .pay(res)
              .then(() => this.paySuccess({ orderId: options.orderId, orderType: this.options.orderType }))
              .catch(() => this.options.fail && this.options.fail({ orderId: options.orderId }))
          } else if (type === "wxScheme") {
            uni.$auth.sdk.pay(res)
          }
        })
      } else {
        return uni.$toast("请选择支付方式")
      }
    },
    /**
     * @description 支付成功跳转
     */
    paySuccess(query) {
      this.close() // 关闭支付组件
      const { orderType, orderId } = query
      if (this.options.success) {
        uni.$on("pay-success", () => {
          uni.$off("pay-success")
          this.options.success({ orderType, orderId, emitFlag: true })
        })
      }
      const vip = (orderType == "film" && this.options.preInfo?.checkVipCardV2Info?.ruleId) || orderType == "equityCard"
      this.toView({
        url: "pages/pay/wait/wait",
        params: { orderType, orderId, vip },
        type: this.options.jumpType
      })
    },
    /**
     * @description 支付失败
     */
    payError(err, query) {
      this.close() // 关闭支付组件
      if (err.errMsg.indexOf("cancel") === -1) {
        this.toView({
          url: "pages/pay/pay-error/pay-error",
          type: "reLaunch"
        })
      } else {
        this.options.fail && this.options.fail(query)
      }
    }
  }
}
